package priv.tuyou.convertor;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.beanutils.Converter;

public class DateTimeConverter implements Converter {
	
	private SimpleDateFormat[] datePattern = new SimpleDateFormat[]{
			new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"),
			new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"),
			new SimpleDateFormat("yyyy-MM-dd"),
			new SimpleDateFormat("HH:mm:ss"),
			new SimpleDateFormat("HH:mm")};

	@Override
	public Object convert(Class arg0, Object arg1) {
		
		if(arg1 == null){
			
			return null;
		}
		
		if(arg0 == Date.class){
			
			if(arg1 instanceof String){
				
				String date = arg1.toString();
				for(SimpleDateFormat format : datePattern){
					
					try {
						return format.parse(date);
					} catch (ParseException e) {
						e.printStackTrace();
					}
				}
				return null;
			}else if(arg1 instanceof Timestamp){
				
				Timestamp timestamp = (Timestamp)arg1;
				return new Date(timestamp.getTime());
			}else if(arg1 instanceof Date){
				
				return arg1;
			}
		}
		return null;
	}
}
